package com.qidianit.mes.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.Supplier;
import com.qidianit.mes.pojo.pro.Process;
import com.qidianit.mes.sys.mapper.SupplierMapper;
import com.qidianit.mes.sys.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: YanJiRan
 * @Date: 2025/9/16 - 下午7:48
 */
@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierMapper supplierMapper;
    @Override
    public Result<PageInfo<Supplier>> selectList(Supplier supplier, int pageNum, int pageSize) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        List<Supplier> suppliers = supplierMapper.selectList(supplier);
        return Result.success(new PageInfo<>(suppliers));
    }

    @Override
    public Result<Supplier> selectByCode(String code) {
        return Result.success(supplierMapper.selectByCode(code));
    }

    @Override
    public Result<Supplier> saveSupplier(Supplier supplier) {
        Supplier supplier1 = supplierMapper.selectByCode(supplier.getCode());
        if (supplier1 != null) {
            return Result.error("供应商编码已存在，请更换编码后重试");
        }
        return supplierMapper.saveSupplier(supplier) == 1 ? Result.success(supplier) : Result.error("操作失败");
    }

    @Override
    public Result<Supplier> updateById(Supplier supplier) {
        //先根据编码查询是否存在相同编码的工序
        Supplier supplier1 = supplierMapper.selectByCode(supplier.getCode());
        //如果存在相同编码的工序
        if (supplier1 != null) {
            //检查id是否相同，不同则说明编码重复
            if (!supplier1.getId().equals(supplier.getId())) {
                return Result.error("供应商编码已存在，请更换编码后重试");
            }
        }
        return supplierMapper.updateById(supplier) == 1 ? Result.success(supplier) : Result.error("操作失败");
    }

    @Override
    public Result deleteById(Long id) {
        return supplierMapper.deleteById(id) == 1 ? Result.success() : Result.error("操作失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return supplierMapper.batchDelete(ids) > 0?Result.success():Result.error("删除失败");
    }
}
